import vue from 'vue'

import vuex from 'vuex'
import axios from 'axios'
vue.use(vuex)// 给组件 添加 $store 

const store = new vuex.Store({
    state: {
        goodslist: []
    },
    mutations: {
        changelist(state, val) {
            state.goodslist = val
            // console.log(val);
        },
        controlbig(state, val) {
            state.goodslist.forEach(item => {
                item.goods_state = val
            });
            console.log(val);
        },
        add(state, id) {
            state.goodslist.forEach(item => {
                if (item.id == id) {
                    item.goods_count++
                }
            })
        },
        reduce(state, id) {
            state.goodslist.forEach(item => {
                if (item.id == id && item.id > 1) {
                    item.goods_count--
                }
            })
        }
    },
    actions: {
        async getgoods(store) {
            let res = await axios({
                url: "/api/cart"
            })
            store.commit('changelist', res.data.list)
        },

    },
    getters: {
        bigcheckbox(state) {
            return state.goodslist.every((item) => item.goods_state === true)
        },


        allcount(state) {
            return state.goodslist.reduce((sum, item) => {
                if (item.goods_state) {
                    sum += item.goods_count * item.goods_price
                }
                return sum
            }, 0)
        },
        howmany(state) {
            return state.goodslist.reduce((sum, item) => {
                if (item.goods_state) {
                    sum += item.goods_count
                }
                return sum
            }, 0)
        }
    }
})

export default store
